<?php

use Zend\Crypt\Utils;
class Admin_ArticleController extends Zend_Controller_Action
{
    private $_config = null;
    public function init()
    {
        $this->_config = Utils_Global::getConfig('admin', 'upload');
        $this->view->articleclzz = 'active';
    }
    
    public function editAction() {
        $id = trim(Utils_Global::$params['id']);
        $categoryModel = Admin_Model_Category::factory();
        $categories = $categoryModel->getCategories();
        if($id) {//Edit
            $articleModel = Admin_Model_Article::factory();
            $article = $articleModel->getArticles(array('id' => $id));
            $article = array_values($article);
            $this->view->article = $article[0];
            $this->view->enTranslationSeoTitle = $article[0]['seo_titles']['en'];
            $this->view->viTranslationSeoTitle = $article[0]['seo_titles']['vi'];
            $this->view->enTranslationSeoDescription = $article[0]['seo_descriptions']['en'];
            $this->view->viTranslationSeoDescription = $article[0]['seo_descriptions']['vi'];
            $this->view->enTranslationSeoKeyword = $article[0]['seo_keywords']['en'];
            $this->view->viTranslationSeoKeyword = $article[0]['seo_keywords']['vi'];
            
            $this->view->id = $id;
            $this->view->title = "Chỉnh sửa tin tức";
            $this->view->errMessage = Utils_Global::$params['errMessage'];
        } else {//Insert
            $this->view->article = Utils_Global::$params;
            $this->view->title = "Tạo tin tức mới";
            $this->view->errMessage = Utils_Global::$params['errMessage'];
        }
        $this->view->categories = $categories;
    }
    
    public function listAction() {
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $userName = $identity->username;
        if($userName == 'admin') {
            $userName = '';
        }
        
        $page = intval(Utils_Global::$params['page']);
        $limit = intval(Utils_Global::$params['limit']);
        $id = Utils_Global::$params['id'];
        $title = Utils_Global::$params['title'];
        $editor = Utils_Global::$params['editor'];
        $category = Utils_Global::$params['category'];
        $active = trim(Utils_Global::$params['active']);
        $datelineF = strtotime(Utils_Global::$params['datelineF']);
        $datelineT = strtotime(Utils_Global::$params['datelineT']);
        $sortBy = Utils_Global::$params['sort_by'];
        $sortDir = Utils_Global::$params['sort_dir'];
        if($limit <= 0) {
            $limit = 10;
        }
        if($page <= 0) {
            $page = 1;
        }

        $modelCategory = Admin_Model_Category::factory();
        $categories = $modelCategory->getCategories();
        
        $modelArticle = Admin_Model_Article::factory();
        $options = array('id' => $id, 'title' => $title, 'category' => $category, 'active' => $active, 'editor' => $userName,
                        'datelineF' => $datelineF, 'datelineT' => $datelineT, 'order' => $sortBy, 'by' => $sortDir?'DESC':'ASC',
                            'offset' => ($page - 1) * $limit, 'limit' => $limit);
        if($editor) {
            $options['editor'] = $editor;
        }
        $articles = $modelArticle->getArticles($options);
        $sortByCol = 'sortBy'.$sortBy;
        $this->view->{$sortByCol} = 1;
        $this->view->sortDir = $sortDir;
        if($sortDir) {
            $this->view->clzzSort = 'icon-chevron-down';
        } else {
            $this->view->clzzSort = 'icon-chevron-up';
        }
        
        $options['sort_by'] = $sortBy;
        $options['sort_dir'] = $sortDir;
        $this->view->params = $options;
        $this->view->articles = $articles;
        $this->view->categories = $categories;
        $this->view->title = "Tin tức";
        $this->view->page = $page;
        $this->view->numRowPerPage = $limit;
        $this->view->totalItem = $modelArticle->getArticlesCount($options);
        $this->view->currentUrl = $this->view->serverUrl() . $this->view->url(array()) . '?' . http_build_query($options);
        $this->view->errMessage = Utils_Global::$params['errMessage'];
    }
    
    public function saveAction() {
        $id = Utils_Global::$params['id'];
        $enTitle = Utils_Global::$params['en_title'];
        $viTitle = Utils_Global::$params['vi_title'];
        $enSeoTitleId = Utils_Global::$params['en_seo_title_id'];
        $viSeoTitleId = Utils_Global::$params['vi_seo_title_id'];
        $enShortDescription = Utils_Global::$params['en_short_description'];
        $viShortDescription = Utils_Global::$params['vi_short_description'];
        $enContent = Utils_Global::$params['en_content'];
        $viContent = Utils_Global::$params['vi_content'];
        $enSeoDescriptionId = Utils_Global::$params['en_seo_description_id'];
        $viSeoDescriptionId = Utils_Global::$params['vi_seo_description_id'];
        $enSeoKeywordId = Utils_Global::$params['en_seo_keyword_id'];
        $viSeoKeywordId = Utils_Global::$params['vi_seo_keyword_id'];
        $enSeoTitle = Utils_Global::$params['en_seo_title'];
        $viSeoTitle = Utils_Global::$params['vi_seo_title'];
        $enSeoDescription = Utils_Global::$params['en_seo_title'];
        $viSeoDescription = Utils_Global::$params['vi_seo_title'];
        $enSeoKeywords = Utils_Global::$params['en_seo_keywords'];
        $viSeoKeywords = Utils_Global::$params['vi_seo_keywords'];
        $order = Utils_Global::$params['order'];
        $enTitleSeo = Utils_CommonFunction::getNameSeo($enTitle);
        $viTitleSeo = Utils_CommonFunction::getNameSeo($viTitle);
        $category = Utils_Global::$params['category'];
        $active = trim(Utils_Global::$params['active']);
        
        if($active) {
            $active = 1;
        }
        $auth = Zend_Auth::getInstance();
        $userName = $auth->getIdentity()->username;
        if(!$userName) {
            $this->_redirect('/admin/auth');
        }
        if(!$enTitleSeo) {
        	Utils_Global::$params['errMessage'] = 'Vui lòng nhập tên bài hợp lệ!';
        	$this->_forward('edit', 'article', 'admin');
        	return;
        }
        
        if($this->_request->isPost()) {
            //Insert into I18n
            $i18nModel = Admin_Model_I18n::factory();
            $translationModel = Admin_Model_Translation::factory();
            if($id && $enId && $viId && $enSeoTitleId && $viSeoTitleId && $enSeoDescriptionId
                    && $viSeoDescriptionId && $enSeoKeywordId && $viSeoKeywordId) {//Update
            	//Insert into translation
            	$translation = array('seo_title' => $enTitleSeo, 'content' => $enTitle,
            			'last_update' => time());
            	$translationModel->update($enId, $translation);//update en
            	$translation['seo_title'] = $viTitleSeo;
            	$translation['content'] = $viTitle;
            	$translationModel->update($viId, $translation);//update vi
            	//Update seo title
            	$data = array('content' => $enSeoTitle, 'last_update' => time());
            	$translationModel->update($enSeoTitleId, $data);
            	$data = array('content' => $viSeoTitle, 'last_update' => time());
            	$translationModel->update($viSeoTitleId, $data);
            	//Update seo description
            	$data = array('content' => $enSeoDescription, 'last_update' => time());
            	$translationModel->update($enSeoDescriptionId, $data);
            	$data = array('content' => $viSeoDescription, 'last_update' => time());
            	$translationModel->update($viSeoDescriptionId, $data);
            	//Update seo keywords
            	$data = array('content' => $enSeoKeywords, 'last_update' => time());
            	$translationModel->update($enSeoKeywordId, $data);
            	$data = array('content' => $viSeoKeywords, 'last_update' => time());
            	$translationModel->update($viSeoKeywordId, $data);
            } else {//Insert
            	 //Insert title
                $i18nId1 = $i18nModel->insert(array());
                Utils_CommonFunction::insertTranslation($enTitle, $enTitleSeo, 'en', $i18nId1);
                Utils_CommonFunction::insertTranslation($viTitle, $viTitleSeo, 'vi', $i18nId1);
                //Insert short description
                $i18nId2 = $i18nModel->insert(array());
                Utils_CommonFunction::insertTranslation($enShortDescription, '', 'en', $i18nId2);
                Utils_CommonFunction::insertTranslation($viShortDescription, '', 'vi', $i18nId2);
                //Insert content
                $i18nId3 = $i18nModel->insert(array());
                Utils_CommonFunction::insertTranslation($enContent, '', 'en', $i18nId3);
                Utils_CommonFunction::insertTranslation($viContent, '', 'vi', $i18nId3);
                
                //Insert seo title
                $i18nIdSeoTitle = $i18nModel->insert(array());
                $data = array('i18n_id' => $i18nIdSeoTitle, 'lang' => 'en',
                		'seo_title' => '', 'content' => $enSeoTitle,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                $data = array('i18n_id' => $i18nIdSeoTitle, 'lang' => 'vi',
                		'seo_title' => '', 'content' => $viSeoTitle,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                //Insert seo description
                $i18nIdSeoDescription = $i18nModel->insert(array());
                $data = array('i18n_id' => $i18nIdSeoDescription, 'lang' => 'en',
                		'seo_title' => '', 'content' => $enSeoDescription,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                $data = array('i18n_id' => $i18nIdSeoDescription, 'lang' => 'vi',
                		'seo_title' => '', 'content' => $viSeoDescription,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                //Insert seo keyword
                $i18nIdSeoKeyword = $i18nModel->insert(array());
                $data = array('i18n_id' => $i18nIdSeoKeyword, 'lang' => 'en',
                		'seo_title' => '', 'content' => $enSeoKeywords,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                $data = array('i18n_id' => $i18nIdSeoKeyword, 'lang' => 'vi',
                		'seo_title' => '', 'content' => $viSeoKeywords,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
            }
            
            $data = array();
            $data = array(
            		'i18n_title' => $i18nId1,
            		'i18n_short_description' => $i18nId2,
            		'i18n_content' => $i18nId3,
                    'i18n_seo_title' => $i18nIdSeoTitle,
                    'i18n_seo_description' => $i18nIdSeoDescription,
                    'i18n_seo_keywords' => $i18nIdSeoKeyword,
            		'category' => $category,
            		'last_update' => time(),
                    'active' => $active,
            		'order' => $order,
            );
            
            $result = $this->uploadTempImage('article');
            if(is_array($result) && $result) {//Luu thong tin upload
            	$data['image'] = $result['image'];
            	$data['hash_folder'] = $result['hash_folder'];
            }
                
            //Save change or insert new
            $articleModel = Admin_Model_Article::factory();
            if($id) {
            	$result = $articleModel->update($id, $data);
            } else {
                $data['editor'] = $userName;
            	$data['dateline'] = time();
            	$result = $articleModel->insert($data);
            }
            
        }
        if($result > 0) {
        	Utils_Global::$params['errMessage'] = "Thay đổi thành công";
            $this->_forward('edit', 'article', 'admin');
        } else {
            Utils_Global::$params['errMessage'] = $errMessage;
            $this->_forward('edit', 'article', 'admin');
            return;
        }
    }
    
    public function deleteAction() {
        $id = Utils_Global::$params['id'];
        $model = Admin_Model_Article::factory();
        $result = $model->delete($id);
        if($result) {
        	$errMessage = "Xóa thành công";
        } else {
        	$errMessage = "Xóa không thành công, vui lòng thử lại!";
        }
        $this->_redirect('/admin/article/list/?errMessage=' . $errMessage);
    }
    
    /**
     * upload into temp folder;
     * @param string $category$category : article or course etc
     * @return 0: lỗi ko xác định, -1: file type ko phù hợp, -2: size vượt quá quy định
     *
     * */
    public function uploadTempImage($category) {
    	try{
    		$upload = new Zend_File_Transfer_Adapter_Http();
    		$files = $upload->getFileInfo();
    		$imagePath = $upload->getFileName();
    		$key = $category.'AvatarUploadPath';
    		$imageUploadPath    = $this->_config->upload->$key;
    		$imageFileName      = '';
    		if($files['file']) {
    		    if(!$files['file']['name']) {
    		        return 0;
    		    }
    			//Check file valid
    			if(!$files['file']['name'] || !preg_match('/jpg|jpeg|gif|png|bmp/', strtolower($files['file']['name']))) {
    				return -1;
    			}
    			 
    			//Check file type is valid or not
    			$allowTypes = $this->_config->upload->acceptedFileTypes->toArray();
    			if(!in_array($files['file']['type'], $allowTypes)) {
    				return -1;//Invalid file
    			}
    			//Check size
    			$source_size = $files['file']['size'];
    			if($source_size > $this->_config->upload->maxFileSizeUpload) {
    				return -2;//Oversize
    			}
    			//Image chapter file name
    			$originalImageFileName = str_replace(' ', '', basename($imagePath));
    			$imageFileName = $originalImageFileName;
    			$ext = pathinfo($imageFileName, PATHINFO_EXTENSION);
    			$imageFileName = time() . $imageFileName;
    			$imageFileName = $imageFileName . '.' . $ext;
    
    			$imageUploadPath = $this->createTempFolder($imageUploadPath, $originalImageFileName);
    			$upload->setDestination($imageUploadPath);
    			$wh = explode('x', $this->_config->imageArticleScale);
    			$upload->addFilter(new Skoch_Filter_File_Resize(array('width' => $wh[0], 'height' => $wh[1], 'keepRatio' => true)));
    			$upload->addFilter('Rename', array('target' => $imageUploadPath . '/' . $imageFileName));
    			$result = $upload->receive();
    			//Tien hanh check type 1 lan nua, make sure day la file hinh
    			$fileType = mime_content_type($imageUploadPath . '/' . $imageFileName);
    			if(!in_array($fileType, $allowTypes)) {
    				unlink($imageUploadPath . '/' . $imageFileName);
    				return -1;//Invalid file
    			}
    			 
    			$imageSize = getimagesize($imageUploadPath . '/' . $imageFileName);
    			if(!$imageSize) {
    				unlink($imageUploadPath . '/' . $imageFileName);
    				return -1;
    			}
    			if($imageSize[0] < $this->_config->upload->dimentionW || $imageSize[1] < $this->_config->upload->dimentionH) {
    				unlink($imageUploadPath . '/' . $imageFileName);
    				return -3;
    			}
    		} else {
    		    return -4;
    		}
    		 
    		$rResult = array();
    		if($result) {
    			$rResult['source_size'] = $source_size;
    			$rResult['image'] = $imageFileName;
    			$rResult['hash_folder'] = Utils_Global::hashName($originalImageFileName, 512);
    		}
    		 
    		return $rResult;
    	} catch(Exception $e) {
    		return 0;
    	}
    }
    
    private function createTempFolder($imageUploadPath, $userName) {
    	//If source is not existed
    	if(!file_exists($imageUploadPath)) {
    		mkdir($imageUploadPath);
    	}
    	 
    	$hashName = Utils_Global::hashName($userName, 512);
    	$imageUploadPath .= '/' . $hashName;
    	if(!file_exists($imageUploadPath)) {
    		mkdir($imageUploadPath);
    	}
    	 
    	return $imageUploadPath;
    }
}

